<template>
  <div>
    <n-button size="medium" @click="updatemodalOpen">修改交易密码</n-button>
    <n-modal v-model:show="changePassword" :mask-closable="false" preset="dialog" title="修改密码">
      <n-form :model="model" ref="formRef" :rules="rules">
        <n-form-item label="商户号" path="custNo">
          <n-input
            v-model:value="model.custNo"
            placeholder="输入商户号"
            :show-button="false"
            style="width: 100%"
            maxlength="30"
            disabled
          />
        </n-form-item>
        <n-form-item path="oldTxPwd" label="当前交易密码" style="margin-top: 10px">
          <n-input
            v-model:value="model.oldTxPwd"
            @keydown.enter.prevent
            type="password"
            maxlength="30"
          />
        </n-form-item>
        <n-form-item path="password" label="新密码" style="margin-top: 10px">
          <n-input
            v-model:value="model.password"
            @input="handlePasswordInput"
            type="password"
            @keydown.enter.prevent
            maxlength="30"
          />
        </n-form-item>
        <n-form-item
          first
          path="NewTxPwd"
          label="确认密码"
          ref="rPasswordFormItemRef"
          style="margin-top: 10px"
        >
          <n-input
            :disabled="!model.password"
            v-model:value="model.NewTxPwd"
            type="password"
            @keydown.enter.prevent
            maxlength="30"
          />
        </n-form-item>
        <n-space justify="right">
          <n-form-item>
            <n-space>
              <n-button @click="changePassword = false" size="medium" strong secondary
                >取消</n-button
              >
              <n-button
                @click="handleValidateButtonClick"
                attr-type="button"
                size="medium"
                type="info"
                >确认</n-button
              >
            </n-space>
          </n-form-item>
        </n-space>
      </n-form>
    </n-modal>
  </div>
</template>

<script lang='ts' setup>
import { ref } from 'vue';
import { updateTragePassword } from '@/api/tragePassword/updateTragePassword';
import { useMessage } from 'naive-ui';
import { log } from 'console';
import { createStorage } from '@/utils/Storage';
import md5 from 'js-md5';

const Storage = createStorage({ storage: localStorage });

const changePassword = ref(false); // 是否显示模态框

const formRef = ref(null);

const rPasswordFormItemRef = ref(null); // 确认密码框值

function updatemodalOpen() {
  clear();
  changePassword.value = true;
  let custNoValue = Storage.get('custNo');
  modelRef.value.custNo = custNoValue
}
const message = useMessage();

const modelRef = ref({
  custNo: '',
  oldTxPwd: '',
  password: '',
  NewTxPwd: '',
});

// 判断第二次密码与第一次是否一样（输入过程中判断）
function validatePasswordStartWith(rule, value) {
  return (
    modelRef.value.password &&
    modelRef.value.password.startsWith(value) &&
    modelRef.value.password.length >= value.length
  );
}

// 判断第二次密码与第一次是否一样（失去焦点判断）
function validatePasswordSame(rule, value) {
  return value === modelRef.value.password;
}

const model = modelRef;

// 表单验证规则
const rules = {
  custNo: [
    {
      required: true,
      message: '请输入商户号',
      trigger: 'blur',
    },
  ],
  oldTxPwd: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur',
    },
  ],
  password: [
    {
      required: true,
      validator(rule, value) {
        if (!value) {
          return new Error('请输入密码');
        } else if (!/^\d{6}$/.test(value)) {
          return new Error('交易密码最多为六位');
        } else {
          return true;
        }
      },
      trigger: 'blur',
    },
  ],
  NewTxPwd: [
    {
      required: true,
      message: '请再次输入密码',
      trigger: ['input', 'blur'],
    },
    {
      validator: validatePasswordStartWith,
      message: '两次密码输入不一致',
      trigger: 'input',
    },
    {
      validator: validatePasswordSame,
      message: '两次密码输入不一致',
      trigger: ['blur', 'password-input'],
    },
  ],
};

const handlePasswordInput = () => {
  if (modelRef.value.NewTxPwd) {
    rPasswordFormItemRef.value.validate({ trigger: 'password-input' });
  }
};

const handleValidateButtonClick = (e) => {
  console.log(modelRef.value);
  e.preventDefault();
  formRef.value.validate((errors) => {
    if (!errors) {
      modelRef.value.oldTxPwd = md5(modelRef.value.oldTxPwd)
      modelRef.value.NewTxPwd = md5(modelRef.value.NewTxPwd)
      modelRef.value.password = md5(modelRef.value.password)
      updateTragePassword(modelRef.value).then((val) => {
        console.log(val);
        if (val.data.sysHead.retCd == '000000') {
          message.success('修改交易密码成功');
          clear();
          changePassword.value = false;
        } else {
          message.error('修改交易密码失败');
          clear();
        }
      });
    } else {
      message.error('修改交易密码失败');
    }
  });
};

// 点击叉号关闭 清空输入框值
const clear = () => {
  modelRef.value.oldTxPwd = '';
  modelRef.value.password = '';
  modelRef.value.NewTxPwd = '';
  modelRef.value.custNo = '';
};

const updatePassword = (parm) => {
  updateTragePassword(parm).then((val) => {
    console.log(val);
  });
};
</script>